import SwiftUI
import AppKit
#if canImport(EventKit)
import EventKit
#endif

/// A calendar view that displays a monthly calendar with Chinese lunar calendar and festivals
struct CalendarView: View {
    @State private var currentDate = Date()
    @State private var selectedDate: Date?
    @State private var opacity: Double = 1.0
    @State private var showWeekNumbers: Bool = false
    @State private var themeColor: Color = .blue
    #if canImport(EventKit)
    @State private var calendarEvents: [EKEvent] = []
    @State private var eventManager: CalendarEventManager?
    #endif
    
    var body: some View {
        ZStack {
            // 毛玻璃背景 - 覆盖整个界面
            VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                .frame(width: 280, height: 380)
                .cornerRadius(12)
            
            VStack(spacing: 0) {
                // Header with month navigation - 固定高度
                HStack {
                    Button("◀") {
                        navigateToPreviousMonth()
                    }
                    .buttonStyle(PlainButtonStyle())
                    .foregroundColor(themeColor)
                    
                    // 年月下拉选择
                    HStack(spacing: 4) {
                        // 年份选择
                        Menu {
                            ForEach(1949...2100, id: \.self) { year in
                                Button("\(year)年") {
                                    let newDate = updateYear(date: currentDate, year: year)
                                    currentDate = newDate
                                    selectedDate = nil
                                }
                            }
                        } label: {
                            HStack(spacing: 2) {
                                Text(String(format: "%d年", Calendar.current.component(.year, from: currentDate)))
                                    .font(.headline)
                                    .fontWeight(.semibold)
                                Image(systemName: "chevron.down")
                                    .font(.caption2)
                            }
                            .foregroundColor(.primary)
                        }
                        .buttonStyle(PlainButtonStyle())
                        
                        // 月份选择
                        Menu {
                            ForEach(1...12, id: \.self) { month in
                                Button("\(String(format: "%02d", month))月") {
                                    let newDate = updateMonth(date: currentDate, month: month)
                                    currentDate = newDate
                                    selectedDate = nil
                                }
                            }
                        } label: {
                            HStack(spacing: 2) {
                                Text("\(String(format: "%02d", Calendar.current.component(.month, from: currentDate)))月")
                                    .font(.headline)
                                    .fontWeight(.semibold)
                                Image(systemName: "chevron.down")
                                    .font(.caption2)
                            }
                            .foregroundColor(.primary)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    
                    Button("▶") {
                        navigateToNextMonth()
                    }
                    .buttonStyle(PlainButtonStyle())
                    .foregroundColor(themeColor)
                    
                    Spacer()
                    
                    Button("今天") {
                        currentDate = Date()
                        selectedDate = nil
                    }
                    .font(.caption)
                }
                .frame(height: 30)
                .padding(.horizontal, 12)
                .padding(.top, 8)
                
                // Day of week headers - 固定高度
                HStack(spacing: 0) {
                    ForEach(["日", "一", "二", "三", "四", "五", "六"], id: \.self) { day in
                        Text(day)
                            .font(.system(size: 13, weight: .medium))
                            .frame(width: 36, height: 20)
                            .foregroundColor(.secondary)
                    }
                }
                .padding(.horizontal, 12)
                .padding(.top, 4)
                
                // Calendar grid - 固定高度
                LazyVGrid(columns: Array(repeating: GridItem(.fixed(36), spacing: 2), count: 7), spacing: 1) {
                    ForEach(daysInMonth(for: currentDate)) { date in
                        Button(action: {
                            if !date.isEmpty {
                                selectedDate = date.date
                            }
                        }) {
                            VStack(spacing: 0) {
                                // 日期数字和选中圆圈 - 固定区域
                                ZStack {
                                    // 放假日期背景色
                                    if date.isHoliday {
                                        RoundedRectangle(cornerRadius: 4)
                                            .fill(Color.red.opacity(0.15))
                                            .frame(width: 32, height: 26)
                                    }
                                    
                                    // 选中圆圈背景
                                    if date.isToday {
                                        Circle()
                                            .fill(themeColor)
                                            .frame(width: 26, height: 26)
                                    } else if selectedDate != nil && calendar.isDate(date.date, inSameDayAs: selectedDate!) {
                                        Circle()
                                            .stroke(themeColor, lineWidth: 2)
                                            .frame(width: 26, height: 26)
                                    }
                                    
                                    // 日期数字
                                    if !date.isEmpty {
                                        Text("\(date.day)")
                                            .font(.system(size: 14, weight: .medium))
                                            .foregroundColor(date.isToday ? .white : (date.isHoliday ? .red : .primary))
                                    }
                                }
                                .frame(width: 36, height: 28)
                                
                                // 节假日标识区域 - 固定高度
                                ZStack {
                                    if !date.isEmpty {
                                        if date.isFestival {
                                            // 节假日名称优先显示（如国庆节、中秋节等）
                                            let festivals = getAllFestivals(for: date.date)
                                            if !festivals.isEmpty {
                                                Text(festivals.first!)
                                                    .font(.system(size: 11, weight: .medium))
                                                    .foregroundColor(themeColor)
                                                    .lineLimit(1)
                                                    .minimumScaleFactor(0.6)
                                            }
                                        } else if let holidayMark = date.holidayMark {
                                            // 放假/调班标记（只在无节日名称时显示）
                                            Text(holidayMark)
                                                .font(.system(size: 10, weight: .bold))
                                                .foregroundColor(holidayMark == "休" ? .red : .blue)
                                                .padding(.horizontal, 3)
                                                .padding(.vertical, 1)
                                                .background(holidayMark == "休" ? Color.red.opacity(0.1) : Color.blue.opacity(0.1))
                                                .cornerRadius(3)
                                        } else if !date.solarTerm.isEmpty {
                                            // 节气用文字
                                            Text(date.solarTerm)
                                                .font(.system(size: 9, weight: .regular))
                                                .foregroundColor(.secondary)
                                                .lineLimit(1)
                                                .minimumScaleFactor(0.7)
                                        }
                                    }
                                }
                                .frame(width: 36, height: 12)
                            }
                            .frame(width: 36, height: 40)
                        }
                        .buttonStyle(PlainButtonStyle())
                        .disabled(date.isEmpty)
                    }
                }
                .frame(height: 250) // 调整日历网格高度
                .padding(.horizontal, 12)
                .padding(.top, 2)
                
                // 固定分隔线
                Divider()
                    .padding(.horizontal, 12)
                    .padding(.top, 6)
                
                // 日期详情区域 - 固定高度，内容滚动
                ScrollView {
                    VStack(alignment: .leading, spacing: 2) {
                        let displayDate = selectedDate ?? Date()
                        
                        HStack(spacing: 4) {
                            Image(systemName: "calendar")
                                .font(.system(size: 12))
                                .foregroundColor(themeColor)
                            Text(fullDateString(for: displayDate))
                                .font(.system(size: 13, weight: .medium))
                                .foregroundColor(themeColor)
                        }
                        
                        let lunarDateString = ChineseCalendarHelper.lunarDate(for: displayDate)
                        Text("农历: \(lunarDateString)")
                            .font(.system(size: 11))
                            .foregroundColor(.secondary)
                        
                        // 闰月特别提示
                        if lunarDateString.contains("闰") {
                            Text("🌙 今年是闰六月年")
                                .font(.system(size: 10))
                                .foregroundColor(.orange)
                        }
                        
                        let festivals = getAllFestivals(for: displayDate)
                        if !festivals.isEmpty {
                            Text("节日: \(festivals.joined(separator: ", "))")
                                .font(.system(size: 11))
                                .foregroundColor(.red)
                        }
                        
                        // 显示日历事件
                        #if canImport(EventKit)
                        if #available(macOS 14.0, *) {
                            if let eventManager = eventManager {
                                let events = eventManager.fetchEvents(for: displayDate)
                                if !events.isEmpty {
                                    Divider()
                                        .padding(.vertical, 2)
                                    
                                    Text("日程安排:")
                                        .font(.system(size: 11, weight: .semibold))
                                        .foregroundColor(.primary)
                                    
                                    ForEach(events.prefix(3), id: \.eventIdentifier) { event in
                                        HStack {
                                            // 显示事件时间
                                            if let startDate = event.startDate {
                                                Text(formatTime(startDate))
                                                    .font(.system(size: 10))
                                                    .foregroundColor(.secondary)
                                                    .frame(width: 35, alignment: .leading)
                                            }
                                            
                                            // 显示事件标题
                                            Text(event.title ?? "无标题")
                                                .font(.system(size: 10))
                                                .foregroundColor(.primary)
                                                .lineLimit(1)
                                            
                                            Spacer()
                                        }
                                    }
                                    
                                    if events.count > 3 {
                                        Text("... 还有 \(events.count - 3) 个事件")
                                            .font(.system(size: 10))
                                            .foregroundColor(.secondary)
                                    }
                                }
                            }
                        }
                        #endif
                    }
                    .frame(maxWidth: .infinity, alignment: .leading)
                }
                .frame(height: 60) // 固定详情区域高度
                .padding(.horizontal, 14)
                .padding(.vertical, 6)
            }
            .frame(width: 280, height: 380) // 整体高度调整
            .opacity(opacity)
            .onAppear {
                // 请求日历访问权限
                #if canImport(EventKit)
                if #available(macOS 14.0, *) {
                    eventManager = CalendarEventManager()
                    eventManager?.checkAuthorizationStatus()
                    if eventManager?.authorizationStatus == .notDetermined {
                        eventManager?.requestAccess()
                    }
                }
                #endif
            }
        }
    }
    
    private func navigateToPreviousMonth() {
        let calendar = Calendar.current
        if let previousMonth = calendar.date(byAdding: .month, value: -1, to: currentDate) {
            currentDate = previousMonth
            selectedDate = nil
        }
    }
    
    private func navigateToNextMonth() {
        let calendar = Calendar.current
        if let nextMonth = calendar.date(byAdding: .month, value: 1, to: currentDate) {
            currentDate = nextMonth
            selectedDate = nil
        }
    }
    
    private func updateYear(date: Date, year: Int) -> Date {
        let calendar = Calendar.current
        var components = calendar.dateComponents([.year, .month, .day], from: date)
        components.year = year
        return calendar.date(from: components) ?? date
    }
    
    private func updateMonth(date: Date, month: Int) -> Date {
        let calendar = Calendar.current
        var components = calendar.dateComponents([.year, .month, .day], from: date)
        components.month = month
        return calendar.date(from: components) ?? date
    }
    
    private func monthYearString(from date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        return formatter.string(from: date)
    }
    
    private func fullDateString(for date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        return formatter.string(from: date)
    }
    
    private func getAllFestivals(for date: Date) -> [String] {
        var festivals: [String] = []
        
        if let solarTerm = ChineseCalendarHelper.solarTerm(for: date) {
            festivals.append(solarTerm)
        }
        
        if let chineseFestival = ChineseCalendarHelper.chineseFestival(for: date) {
            festivals.append(chineseFestival)
        }
        
        if let internationalFestival = ChineseCalendarHelper.internationalFestival(for: date) {
            festivals.append(internationalFestival)
        }
        
        return festivals
    }
    
    private func formatTime(_ date: Date) -> String {
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "HH:mm"
        return timeFormatter.string(from: date)
    }
    
    private let calendar = Calendar.current
    
    private func daysInMonth(for date: Date) -> [CalendarDay] {
        let components = calendar.dateComponents([.year, .month], from: date)
        let startOfMonth = calendar.date(from: components)!
        
        // Get the first day of the month to determine starting weekday
        let firstWeekday = calendar.component(.weekday, from: startOfMonth)
        let daysInMonth = calendar.range(of: .day, in: .month, for: startOfMonth)!.count
        
        var days: [CalendarDay] = []
        
        // Add empty days for the first week
        for i in 1..<firstWeekday {
            days.append(CalendarDay(
                id: Double(-i),
                date: Date(timeIntervalSince1970: 0),
                day: 0,
                isToday: false,
                solarTerm: "",
                isFestival: false,
                isHoliday: false,
                holidayMark: nil,
                isEmpty: true
            ))
        }
        
        // Add actual days
        for day in 1...daysInMonth {
            let dateComponent = DateComponents(year: components.year, month: components.month, day: day)
            let dayDate = calendar.date(from: dateComponent)!
            
            let solarTerm = ChineseCalendarHelper.solarTerm(for: dayDate) ?? ""
            let isFestival = ChineseCalendarHelper.chineseFestival(for: dayDate) != nil || 
                            ChineseCalendarHelper.internationalFestival(for: dayDate) != nil
            let isHoliday = ChineseCalendarHelper.isChineseHoliday(for: dayDate)
            let holidayMark = ChineseCalendarHelper.getHolidayMark(for: dayDate)
            
            days.append(CalendarDay(
                id: dayDate.timeIntervalSince1970,
                date: dayDate,
                day: day,
                isToday: calendar.isDateInToday(dayDate),
                solarTerm: solarTerm,
                isFestival: isFestival,
                isHoliday: isHoliday,
                holidayMark: holidayMark,
                isEmpty: false
            ))
        }
        
        return days
    }
}

/// Represents a day in the calendar
struct CalendarDay: Identifiable {
    let id: Double
    let date: Date
    let day: Int
    let isToday: Bool
    let solarTerm: String
    let isFestival: Bool
    let isHoliday: Bool
    let holidayMark: String?
    var isEmpty: Bool = false
}

// MARK: - Previews
struct CalendarView_Previews: PreviewProvider {
    static var previews: some View {
        CalendarView()
    }
}

// MARK: - VisualEffectView for Blur Background
struct VisualEffectView: NSViewRepresentable {
    let material: NSVisualEffectView.Material
    let blendingMode: NSVisualEffectView.BlendingMode
    
    func makeNSView(context: Context) -> NSVisualEffectView {
        let visualEffectView = NSVisualEffectView()
        visualEffectView.material = material
        visualEffectView.blendingMode = blendingMode
        visualEffectView.state = .active
        return visualEffectView
    }
    
    func updateNSView(_ visualEffectView: NSVisualEffectView, context: Context) {
        visualEffectView.material = material
        visualEffectView.blendingMode = blendingMode
    }
}